<?php
session_start();
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/version_control.php';
require_once __DIR__ . '/includes/qr_generator.php';

// 添加防缓存头部
addNoCacheHeaders();

// 检查用户登录状态
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

$user_id = $_SESSION['user_id'];
$username = $_SESSION['username'];

try {
    // 获取用户信息
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch();
    
    if (!$user) {
        header('Location: login.php');
        exit;
    }
    
    // 获取团队统计信息
    $team_stats_stmt = $pdo->prepare("
        SELECT 
            COUNT(*) as team_size,
            COALESCE(SUM(tc.commission_amount), 0) as total_commission_earned,
            COALESCE(SUM(tc.commission_amount), 0) as total_commission_paid
        FROM users u
        LEFT JOIN team_commissions tc ON tc.inviter_id = ?
        WHERE u.inviter_id = ?
    ");
    $team_stats_stmt->execute([$user_id, $user_id]);
    $team_stats = $team_stats_stmt->fetch();
    
    // 获取团队成员基本信息
    $team_members_stmt = $pdo->prepare("
        SELECT 
            u.id,
            u.username,
            u.balance,
            u.total_commission,
            u.created_at
        FROM users u
        WHERE u.inviter_id = ?
        ORDER BY u.created_at DESC
    ");
    $team_members_stmt->execute([$user_id]);
    $team_members = $team_members_stmt->fetchAll();
    
    // 为每个成员添加交易统计和分成信息
    foreach ($team_members as &$member) {
        // 获取交易统计
        $transaction_stmt = $pdo->prepare("
            SELECT 
                COUNT(*) as transaction_count,
                COALESCE(SUM(amount), 0) as total_trading_amount,
                COALESCE(SUM(fee), 0) as total_fees_paid
            FROM transactions 
            WHERE user_id = ?
        ");
        $transaction_stmt->execute([$member['id']]);
        $transaction_stats = $transaction_stmt->fetch();
        
        // 获取分成统计
        $commission_stmt = $pdo->prepare("
            SELECT COALESCE(SUM(commission_amount), 0) as commission_earned
            FROM team_commissions 
            WHERE user_id = ? AND inviter_id = ?
        ");
        $commission_stmt->execute([$member['id'], $user_id]);
        $commission_stats = $commission_stmt->fetch();
        
        // 合并数据
        $member['transaction_count'] = $transaction_stats['transaction_count'];
        $member['total_trading_amount'] = $transaction_stats['total_trading_amount'];
        $member['total_fees_paid'] = $transaction_stats['total_fees_paid'];
        $member['commission_earned'] = $commission_stats['commission_earned'];
    }
    
    // 获取最近的手续费分成记录
    $recent_commissions_stmt = $pdo->prepare("
        SELECT 
            tc.*,
            u.username as user_name,
            t.amount as transaction_amount,
            t.fee as original_fee
        FROM team_commissions tc
        JOIN users u ON u.id = tc.user_id
        JOIN transactions t ON t.id = tc.transaction_id
        WHERE tc.inviter_id = ?
        ORDER BY tc.created_at DESC
        LIMIT 20
    ");
    $recent_commissions_stmt->execute([$user_id]);
    $recent_commissions = $recent_commissions_stmt->fetchAll();
    
} catch (PDOException $e) {
    error_log("获取团队信息失败: " . $e->getMessage());
    $team_stats = ['team_size' => 0, 'total_commission_earned' => 0, 'total_commission_paid' => 0];
    $team_members = [];
    $recent_commissions = [];
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>我的团队</title>
    <?php echo getCssLink('assets/css/mobile.css'); ?>
    <link rel="icon" href="<?php echo getVersionedUrl('static/img/logo.png'); ?>" sizes="32x32" type="image/png">
    <style>
        .team-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .team-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 15px;
            margin-bottom: 30px;
            text-align: center;
        }
        
        .team-stats {
            display: flex;
            justify-content: space-between;
            gap: 20px;
            margin-bottom: 30px;
            background: white;
            padding: 25px;
            border-radius: 15px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .stat-card {
            flex: 1;
            text-align: center;
            padding: 15px;
            border-radius: 10px;
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border: 1px solid #e9ecef;
            transition: all 0.3s ease;
        }
        
        .stat-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 20px rgba(102, 126, 234, 0.15);
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .stat-card:hover .stat-value {
            color: white;
        }
        
        .stat-card:hover .stat-label {
            color: rgba(255, 255, 255, 0.9);
        }
        
        .stat-value {
            font-size: 2.2em;
            font-weight: bold;
            color: #667eea;
            margin-bottom: 8px;
            transition: color 0.3s ease;
        }
        
        .stat-label {
            color: #666;
            font-size: 1em;
            font-weight: 500;
            transition: color 0.3s ease;
        }
        
        .stat-icon {
            font-size: 2.5em;
            margin-bottom: 10px;
            opacity: 0.8;
            transition: all 0.3s ease;
        }
        
        .stat-card:hover .stat-icon {
            opacity: 1;
            transform: scale(1.1);
        }
        
        .invite-section {
            background: white;
            padding: 25px;
            border-radius: 15px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }
        
        .invite-code {
            background: #f8f9fa;
            border: 2px dashed #667eea;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            margin: 20px 0;
        }
        
        .qr-code-section {
            background: white;
            padding: 25px;
            border-radius: 15px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            margin-bottom: 30px;
            text-align: center;
        }
        
        .qr-code-container {
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 20px 0;
        }
        
        .qr-code-image {
            max-width: 300px;
            max-height: 300px;
            border: 3px solid #667eea;
            border-radius: 15px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .qr-actions {
            margin-top: 20px;
        }
        
        .qr-btn {
            background: #667eea;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 8px;
            cursor: pointer;
            margin: 5px;
            font-size: 14px;
            transition: all 0.3s ease;
        }
        
        .qr-btn:hover {
            background: #5a6fd8;
            transform: translateY(-2px);
        }
        
        .qr-btn.secondary {
            background: #6c757d;
        }
        
        .qr-btn.secondary:hover {
            background: #5a6268;
        }
        
        .invite-code-text {
            font-size: 1.5em;
            font-weight: bold;
            color: #667eea;
            letter-spacing: 2px;
        }
        
        .copy-btn {
            background: #667eea;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            margin-top: 10px;
        }
        
        .team-members {
            background: white;
            padding: 25px;
            border-radius: 15px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }
        
        .member-card {
            border: 1px solid #eee;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 15px;
            transition: all 0.3s ease;
        }
        
        .member-card:hover {
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            transform: translateY(-2px);
        }
        
        .member-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        
        .member-name {
            font-size: 1.2em;
            font-weight: bold;
            color: #333;
        }
        
        .member-join-date {
            color: #666;
            font-size: 0.9em;
        }
        
        .member-stats {
            display: flex;
            justify-content: space-around;
            gap: 15px;
        }
        
        .member-stat {
            text-align: center;
        }
        
        .member-stat-value {
            font-size: 1.3em;
            font-weight: bold;
            color: #667eea;
        }
        
        .member-stat-label {
            color: #666;
            font-size: 0.9em;
        }
        
        .commissions-section {
            background: white;
            padding: 25px;
            border-radius: 15px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .commission-item {
            border-bottom: 1px solid #eee;
            padding: 15px 0;
        }
        
        .commission-item:last-child {
            border-bottom: none;
        }
        
        .commission-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 5px;
        }
        
        .commission-user {
            font-weight: bold;
            color: #333;
        }
        
        .commission-amount {
            font-weight: bold;
            color: #28a745;
        }
        
        .commission-details {
            color: #666;
            font-size: 0.9em;
        }
        
        .back-btn {
            background:rgb(37, 37, 37);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 50px;
            cursor: pointer;
            margin-bottom: 20px;
        }
        
        .back-btn:hover {
            background: #5a6268;
        }
        
        .share-btn {
            background: linear-gradient(135deg, #ff6b6b 0%, #ff8e53 50%, #ff6b6b 100%);
            background-size: 200% 200%;
            color: white;
            border: none;
            padding: 16px 32px;
            border-radius: 50px;
            cursor: pointer;
            margin-bottom: 20px;
            margin-left: 10px;
            font-size: 18px;
            font-weight: bold;
            transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            box-shadow: 0 8px 25px rgba(255, 107, 107, 0.4);
            position: relative;
            overflow: hidden;
            text-transform: uppercase;
            letter-spacing: 1px;
            animation: pulse-glow 2s infinite;
        }
        
        .share-btn::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
            transition: left 0.6s;
        }
        
        .share-btn:hover::before {
            left: 100%;
        }
        
        .share-btn:hover {
            background: linear-gradient(135deg, #ff5252 0%, #ff7043 50%, #ff5252 100%);
            transform: translateY(-4px) scale(1.05);
            box-shadow: 0 12px 35px rgba(255, 107, 107, 0.6);
            animation: none;
        }
        
        .share-btn:active {
            transform: translateY(-2px) scale(1.02);
            box-shadow: 0 6px 20px rgba(255, 107, 107, 0.5);
        }
        
        @keyframes pulse-glow {
            0% {
                box-shadow: 0 8px 25px rgba(255, 107, 107, 0.4);
            }
            50% {
                box-shadow: 0 8px 25px rgba(255, 107, 107, 0.7), 0 0 20px rgba(255, 107, 107, 0.3);
            }
            100% {
                box-shadow: 0 8px 25px rgba(255, 107, 107, 0.4);
            }
        }
        
        @keyframes background-shift {
            0% {
                background-position: 0% 50%;
            }
            50% {
                background-position: 100% 50%;
            }
            100% {
                background-position: 0% 50%;
            }
        }
        
        .share-btn.animate {
            animation: background-shift 3s ease infinite;
        }
        
        .share-btn .btn-icon {
            font-size: 20px;
            margin-right: 8px;
            display: inline-block;
            animation: bounce 1.5s infinite;
        }
        
        .share-btn .btn-text {
            font-size: 16px;
            font-weight: bold;
        }
        
        .share-btn .btn-badge {
            background: rgba(255, 255, 255, 0.2);
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            margin-left: 8px;
            border: 1px solid rgba(255, 255, 255, 0.3);
            animation: pulse-badge 2s infinite;
        }
        
        @keyframes bounce {
            0%, 20%, 50%, 80%, 100% {
                transform: translateY(0);
            }
            40% {
                transform: translateY(-3px);
            }
            60% {
                transform: translateY(-2px);
            }
        }
        
        @keyframes pulse-badge {
            0% {
                background: rgba(255, 255, 255, 0.2);
                transform: scale(1);
            }
            50% {
                background: rgba(255, 255, 255, 0.3);
                transform: scale(1.05);
            }
            100% {
                background: rgba(255, 255, 255, 0.2);
                transform: scale(1);
            }
        }
        
        .ripple {
            position: absolute;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.6);
            transform: scale(0);
            animation: ripple-animation 0.6s linear;
            pointer-events: none;
        }
        
        @keyframes ripple-animation {
            to {
                transform: scale(4);
                opacity: 0;
            }
        }
        
        /* 分享弹窗样式 */
        .share-modal-content {
            max-width: 600px;
            max-height: 90vh;
            overflow-y: auto;
        }
        
        .share-section {
            margin-bottom: 30px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 10px;
            border: 1px solid #e9ecef;
        }
        
        .share-section h4 {
            color: #667eea;
            margin-bottom: 10px;
            font-size: 1.2em;
        }
        
        .share-section p {
            color: #666;
            margin-bottom: 15px;
            line-height: 1.5;
        }
        
        .share-tips {
            background: #e3f2fd;
            border: 1px solid #bbdefb;
            border-radius: 10px;
            padding: 20px;
        }
        
        .share-tips h4 {
            color: #1976d2;
            margin-bottom: 15px;
        }
        
        .share-tips ul {
            margin: 0;
            padding-left: 20px;
        }
        
        .share-tips li {
            color: #424242;
            margin-bottom: 8px;
            line-height: 1.4;
        }
        
        @media (max-width: 768px) {
            .team-container {
                padding: 10px;
                max-width: 100%;
            }
            
            .team-header {
                padding: 20px;
                margin-bottom: 20px;
            }
            
            .team-header h1 {
                font-size: 1.8em;
                margin-bottom: 10px;
            }
            
            .team-stats {
                gap: 15px;
                margin-bottom: 20px;
                padding: 20px;
            }
            
            .stat-card {
                padding: 20px;
                flex: none;
            }
            
            .stat-value {
                font-size: 2em;
            }
            
            .stat-icon {
                font-size: 2em;
                margin-bottom: 8px;
            }
            
            .invite-section, .qr-code-section, .team-members, .commissions-section {
                padding: 20px;
                margin-bottom: 20px;
            }
            
            .invite-code-text {
                font-size: 1.3em;
                letter-spacing: 1px;
            }
            
            .copy-btn {
                padding: 12px 20px;
                font-size: 14px;
                width: 100%;
                margin-top: 15px;
            }
            
            .qr-code-image {
                max-width: 250px;
                max-height: 250px;
            }
            
            .qr-actions {
                display: flex;
                flex-direction: column;
                gap: 10px;
            }
            
            .qr-btn {
                width: 100%;
                padding: 15px;
                font-size: 16px;
                margin: 5px 0;
            }
            
            .member-stats {
                grid-template-columns: repeat(2, 1fr);
                gap: 10px;
            }
            
            .member-stat-value {
                font-size: 1.1em;
            }
            
            .member-stat-label {
                font-size: 0.8em;
            }
            
            .back-btn {
                width: 100px;
                padding: 15px;
                font-size: 16px;
                margin-bottom: 15px;
            }
            
            .share-btn {
                width: 100%;
                padding: 18px 20px;
                font-size: 16px;
                margin-bottom: 15px;
                margin-left: 0;
                display: flex;
                align-items: center;
                justify-content: center;
                gap: 8px;
            }
            
            .share-btn .btn-icon {
                font-size: 34px;
                margin-right: 0;
            }
            
            .share-btn .btn-text {
                font-size: 15px;
            }
            
            .share-btn .btn-badge {
                font-size: 11px;
                padding: 3px 6px;
                margin-left: 0;
            }
            
            .share-modal-content {
                max-width: 95%;
                margin: 10px;
            }
            
            .share-section {
                padding: 15px;
                margin-bottom: 20px;
            }
            
            .share-tips {
                padding: 15px;
            }
            
            /* 邀请链接输入框优化 */
            #invite-link {
                font-size: 14px;
                padding: 12px;
                margin-bottom: 10px;
            }
            
            /* 使用说明优化 */
            .qr-code-section ul {
                font-size: 14px;
                line-height: 1.6;
            }
            
            /* 分成记录优化 */
            .commission-details {
                font-size: 0.8em;
                line-height: 1.4;
            }
        }
        
        @media (max-width: 480px) {
            .team-container {
                padding: 5px;
            }
            
            .team-header {
                padding: 15px;
            }
            
            .team-header h1 {
                font-size: 1.5em;
            }
            
            .stat-value {
                font-size: 1.8em;
            }
            
            .stat-icon {
                font-size: 1.8em;
                margin-bottom: 6px;
            }
            
            .invite-code-text {
                font-size: 1.2em;
            }
            
            .qr-code-image {
                max-width: 200px;
                max-height: 200px;
            }
            
            .member-stats {
                grid-template-columns: 1fr;
                gap: 8px;
            }
            
            .member-stat {
                padding: 10px;
                background: #f8f9fa;
                border-radius: 8px;
            }
        }
    </style>
</head>
<body>
    <div class="team-container">
        <button class="back-btn" onclick="window.history.back()">返回</button>
        
        <button class="share-btn" onclick="showShareModal()">
            <span class="btn-icon">
               <?php echo getVersionedImg('static/img/sharecoin.png', '提现记录', 'width="40" height="40"'); ?>
             </span>
            <span class="btn-text">立即分享赚佣金</span>
            <span class="btn-badge">40%分成</span>
        </button>
        <!-- 团队统计 -->
        <div class="team-stats">
            <div class="stat-card">
                <div class="stat-value"><?php echo $team_stats['team_size']; ?></div>
                <div class="stat-label">团队成员</div>
            </div>
            <div class="stat-card">
                <div class="stat-value">¥<?php echo number_format($team_stats['total_commission_earned'], 2); ?></div>
                <div class="stat-label">累计分成</div>
            </div>
            <div class="stat-card">
                <div class="stat-value">¥<?php echo number_format($team_stats['total_commission_paid'], 2); ?></div>
                <div class="stat-label">已发放分成</div>
            </div>
        </div>
        
    
        
     
        
        <!-- 团队成员 -->
        <div class="team-members">
            <h3>团队成员 (<?php echo count($team_members); ?>)</h3>
            
            <?php if (empty($team_members)): ?>
                <div style="text-align: center; padding: 40px; color: #666;">
                    <p>暂无团队成员</p>
                    <p>分享您的邀请码，邀请好友加入吧！</p>
                </div>
            <?php else: ?>
                <?php foreach ($team_members as $member): ?>
                    <div class="member-card">
                        <div class="member-header">
                            <div class="member-name"><?php echo htmlspecialchars($member['username']); ?></div>
                            <div class="member-join-date">加入时间：<?php echo date('Y-m-d', strtotime($member['created_at'])); ?></div>
                        </div>
                        
                        <div class="member-stats">
                            <div class="member-stat">
                                <div class="member-stat-value">¥<?php echo number_format($member['balance'], 2); ?></div>
                                <div class="member-stat-label">余额</div>
                            </div>
                            <div class="member-stat">
                                <div class="member-stat-value"><?php echo $member['transaction_count']; ?></div>
                                <div class="member-stat-label">次数</div>
                            </div>
                            <div class="member-stat">
                                <div class="member-stat-value">¥<?php echo number_format($member['total_trading_amount'], 2); ?></div>
                                <div class="member-stat-label">交易总额</div>
                            </div>
                            <div class="member-stat">
                                <div class="member-stat-value">¥<?php echo number_format($member['total_fees_paid'], 2); ?></div>
                                <div class="member-stat-label">手续费总额</div>
                            </div>
                            <div class="member-stat">
                                <div class="member-stat-value">¥<?php echo number_format($member['commission_earned'], 2); ?></div>
                                <div class="member-stat-label">为您赚取</div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
        
        <!-- 最近分成记录 -->
        <div class="commissions-section">
            <h3>最近分成记录</h3>
            
            <?php if (empty($recent_commissions)): ?>
                <div style="text-align: center; padding: 40px; color: #666;">
                    <p>暂无分成记录</p>
                    <p>团队成员交易后，您将获得手续费分成</p>
                </div>
            <?php else: ?>
                <?php foreach ($recent_commissions as $commission): ?>
                    <div class="commission-item">
                        <div class="commission-header">
                            <div class="commission-user"><?php echo htmlspecialchars($commission['user_name']); ?></div>
                            <div class="commission-amount">+¥<?php echo number_format($commission['commission_amount'], 2); ?></div>
                        </div>
                        <div class="commission-details">
                            交易金额：¥<?php echo number_format($commission['transaction_amount'], 2); ?> | 
                            手续费：¥<?php echo number_format($commission['original_fee'], 2); ?> | 
                            分成比例：<?php echo number_format($commission['commission_rate'] * 100, 1); ?>% | 
                            时间：<?php echo date('Y-m-d H:i', strtotime($commission['created_at'])); ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>

    <!-- 分享赚佣金弹窗 -->
    <div class="modal" id="share-modal" style="display: none;">
        <div class="modal-content share-modal-content">
            <div class="modal-header">
                <h3>分享赚佣金</h3>
                <button class="close-btn" onclick="closeModal('share-modal')">&times;</button>
            </div>
            <div class="modal-body">
                <!-- 邀请好友模块 -->
                <div class="share-section">
                    <h4>邀请好友</h4>
                    <p>分享您的邀请码，好友注册后您将获得其交易手续费的40%作为分成</p>
                    
                    <div class="invite-code">
                        <div class="invite-code-text"><?php echo htmlspecialchars($user['invite_code'] ?? '未生成'); ?></div>
                        <button class="copy-btn" onclick="copyInviteLink()">复制邀请链接</button>
                    </div>
                </div>
                
                <!-- 邀请二维码模块 -->
                <div class="share-section">
                    <h4>邀请二维码</h4>
                    <p>好友扫描二维码即可直接注册并建立邀请关系</p>
                    
                    <div class="qr-code-container">
                        <img id="share-qr-code-image" class="qr-image" 
                             src="generate_qr.php?action=generate&t=<?php echo time(); ?>" 
                             alt="邀请二维码"
                             data-qr-url="<?php echo 'http://' . $_SERVER['HTTP_HOST'] . '/login.php?invite=' . urlencode($user['invite_code'] ?? ''); ?>">
                    </div>
                    
                    <div class="qr-actions">
                        <button class="qr-btn" onclick="downloadShareQRCode()">下载二维码</button>
                        <button class="qr-btn secondary" onclick="refreshShareQRCode()">刷新二维码</button>
                    </div>
                </div>
                
                <!-- 分享说明 -->
                <div class="share-tips">
                    <h4>分享说明</h4>
                    <ul>
                        <li>将邀请链接或二维码分享给好友</li>
                        <li>好友通过您的邀请注册后自动建立邀请关系</li>
                        <li>好友交易时您将获得40%手续费分成</li>
                        <li>分成实时到账，可在团队页面查看收益</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 复制邀请码
        function copyInviteCode() {
            const inviteCode = '<?php echo htmlspecialchars($user['invite_code'] ?? ''); ?>';
            
            // 移动端友好的复制方式
            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(inviteCode).then(() => {
                    showToast('邀请码已复制到剪贴板！');
                }).catch(() => {
                    fallbackCopy(inviteCode);
                });
            } else {
                fallbackCopy(inviteCode);
            }
        }
        
        // 降级复制方案
        function fallbackCopy(text) {
            const textArea = document.createElement('textarea');
            textArea.value = text;
            textArea.style.position = 'fixed';
            textArea.style.left = '-999999px';
            textArea.style.top = '-999999px';
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();
            
            try {
                document.execCommand('copy');
                showToast('邀请码已复制到剪贴板！');
            } catch (err) {
                showToast('复制失败，请手动复制：' + text);
            }
            
            document.body.removeChild(textArea);
        }
        
        // 复制邀请链接
        function copyInviteLink() {
            const inviteLink = '<?php echo 'http://' . $_SERVER['HTTP_HOST'] . '/login.php?invite=' . urlencode($user['invite_code'] ?? ''); ?>';
            
            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(inviteLink).then(() => {
                    showToast('邀请链接已复制到剪贴板！');
                }).catch(() => {
                    fallbackCopy(inviteLink);
                });
            } else {
                fallbackCopy(inviteLink);
            }
        }
        
        // 移动端友好的提示功能
        function showToast(message, type = 'info') {
            // 创建提示元素
            const toast = document.createElement('div');
            toast.textContent = message;
            
            const colors = {
                success: '#28a745',
                error: '#dc3545',
                warning: '#ffc107',
                info: '#17a2b8'
            };
            
            toast.style.cssText = `
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background: ${colors[type] || colors.info};
                color: white;
                padding: 15px 25px;
                border-radius: 8px;
                font-size: 16px;
                z-index: 10000;
                max-width: 80%;
                text-align: center;
                box-shadow: 0 4px 15px rgba(0,0,0,0.3);
            `;
            
            document.body.appendChild(toast);
            
            // 3秒后自动消失
            setTimeout(() => {
                if (toast.parentNode) {
                    toast.parentNode.removeChild(toast);
                }
            }, 3000);
        }
        
        // 下载二维码
        async function downloadQRCode() {
            try {
                const qrImage = document.getElementById('qr-code-image');
                if (!qrImage) {
                    showToast('二维码图片未找到', 'error');
                    return;
                }

                showToast('正在生成合成图片...', 'info');

                // 创建背景图片
                const backgroundImg = new Image();
                backgroundImg.crossOrigin = 'anonymous';
                
                // 等待背景图片加载
                await new Promise((resolve, reject) => {
                    backgroundImg.onload = resolve;
                    backgroundImg.onerror = () => {
                        console.warn('背景图片加载失败，使用纯色背景');
                        resolve();
                    };
                    backgroundImg.src = 'static/qrcodes/1.png';
                });

                // 创建画布
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');
                
                // 设置画布尺寸（使用背景图尺寸或默认尺寸）
                if (backgroundImg.naturalWidth > 0) {
                    canvas.width = backgroundImg.naturalWidth;
                    canvas.height = backgroundImg.naturalHeight;
                } else {
                    // 如果背景图加载失败，使用默认尺寸
                    canvas.width = 400;
                    canvas.height = 400;
                }
                
                // 绘制背景
                if (backgroundImg.naturalWidth > 0) {
                    ctx.drawImage(backgroundImg, 0, 0, canvas.width, canvas.height);
                } else {
                    // 绘制纯色背景
                    ctx.fillStyle = '#ffffff';
                    ctx.fillRect(0, 0, canvas.width, canvas.height);
                    
                    // 添加一些装饰
                    ctx.fillStyle = '#667eea';
                    ctx.fillRect(0, 0, canvas.width, 60);
                    
                    // 添加标题文字
                    ctx.fillStyle = '#ffffff';
                    ctx.font = 'bold 24px Arial';
                    ctx.textAlign = 'center';
                    ctx.fillText('邀请二维码', canvas.width / 2, 35);
                }
                
                // 计算二维码在背景中的位置和尺寸（右下角）
                const qrSize = Math.min(canvas.width * 0.6, canvas.height * 0.6, 250);
                const margin = 20; // 距离边缘的边距
                const qrX = canvas.width - qrSize - margin;
                const qrY = canvas.height - qrSize - margin;
                
                // 绘制二维码
                ctx.drawImage(qrImage, qrX, qrY, qrSize, qrSize);
                
                // 添加二维码边框
                ctx.strokeStyle = '#667eea';
                ctx.lineWidth = 3;
                ctx.strokeRect(qrX - 2, qrY - 2, qrSize + 4, qrSize + 4);
                
                // 添加说明文字（在二维码上方）
                ctx.fillStyle = '#333333';
                ctx.font = '12px Arial';
                ctx.textAlign = 'center';
                ctx.fillText('扫描注册', qrX + qrSize / 2, qrY - 10);
                
                // 添加邀请码信息（在二维码下方）
                const inviteCode = '<?php echo htmlspecialchars($user['invite_code'] ?? ''); ?>';
                if (inviteCode && inviteCode !== '未生成') {
                    ctx.fillStyle = '#666666';
                    ctx.font = '10px Arial';
                    ctx.textAlign = 'center';
                    ctx.fillText(`邀请码：${inviteCode}`, qrX + qrSize / 2, qrY + qrSize + 15);
                }
                
                // 转换为blob并下载
                canvas.toBlob(function(blob) {
                    if (!blob) {
                        showToast('图片生成失败', 'error');
                        return;
                    }
                    
                    const url = URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = '邀请二维码_<?php echo htmlspecialchars($username); ?>_<?php echo htmlspecialchars($user['invite_code'] ?? ''); ?>.png';
                    a.style.display = 'none';
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    URL.revokeObjectURL(url);
                    showToast('合成二维码已下载！', 'success');
                }, 'image/png', 0.9);
                
            } catch (error) {
                console.error('下载失败:', error);
                showToast('下载失败: ' + error.message, 'error');
            }
        }
        
        // 刷新二维码
        async function refreshQRCode() {
            try {
                const inviteLink = '<?php echo 'http://' . $_SERVER['HTTP_HOST'] . '/login.php?invite=' . urlencode($user['invite_code'] ?? ''); ?>';
                if (!inviteLink) {
                    showToast('邀请链接未找到', 'error');
                    return;
                }
                
                // 使用新的API生成二维码
                const response = await fetch('/api/generate_qr.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        text: inviteLink,
                        size: 300,
                        error_correction: 'L',
                        margin: 4,
                        module_size: 3
                    })
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const result = await response.json();
                
                if (result.success && result.data && result.data.base64) {
                    const qrImage = document.getElementById('qr-code-image');
                    qrImage.src = result.data.base64;
                    showToast('二维码已刷新', 'success');
                } else {
                    throw new Error(result.error || '二维码生成失败');
                }
                
            } catch (error) {
                console.error('刷新二维码失败:', error);
                showToast('二维码刷新失败', 'error');
            }
        }
        

        
        // 降级分享方案
        async function fallbackShare(shareData) {
            const shareText = `${shareData.text}\n注册链接：${shareData.url}`;
            
            try {
                if (navigator.clipboard && window.isSecureContext) {
                    await navigator.clipboard.writeText(shareText);
                    showToast('分享内容已复制到剪贴板！', 'success');
                } else {
                    fallbackCopy(shareText);
                }
            } catch (error) {
                console.error('分享失败:', error);
                showToast('分享失败', 'error');
            }
        }
        
        // 显示分享弹窗
        function showShareModal() {
            const modal = document.getElementById('share-modal');
            modal.style.display = 'block';
            document.body.style.overflow = 'hidden';
        }
        
        // 关闭弹窗
        function closeModal(modalId) {
            const modal = document.getElementById(modalId);
            modal.style.display = 'none';
            document.body.style.overflow = 'auto';
        }
        
        // 下载分享二维码
        async function downloadShareQRCode() {
            try {
                const qrImage = document.getElementById('share-qr-code-image');
                if (!qrImage) {
                    showToast('二维码图片未找到', 'error');
                    return;
                }

                showToast('正在生成合成图片...', 'info');

                // 创建背景图片
                const backgroundImg = new Image();
                backgroundImg.crossOrigin = 'anonymous';
                
                // 等待背景图片加载
                await new Promise((resolve, reject) => {
                    backgroundImg.onload = resolve;
                    backgroundImg.onerror = () => {
                        console.warn('背景图片加载失败，使用纯色背景');
                        resolve();
                    };
                    backgroundImg.src = 'static/qrcodes/1.png';
                });

                // 创建画布
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');
                
                // 设置画布尺寸（使用背景图尺寸或默认尺寸）
                if (backgroundImg.naturalWidth > 0) {
                    canvas.width = backgroundImg.naturalWidth;
                    canvas.height = backgroundImg.naturalHeight;
                } else {
                    // 如果背景图加载失败，使用默认尺寸
                    canvas.width = 400;
                    canvas.height = 400;
                }
                
                // 绘制背景
                if (backgroundImg.naturalWidth > 0) {
                    ctx.drawImage(backgroundImg, 0, 0, canvas.width, canvas.height);
                } else {
                    // 绘制纯色背景
                    ctx.fillStyle = '#ffffff';
                    ctx.fillRect(0, 0, canvas.width, canvas.height);
                    
                    // 添加一些装饰
                    ctx.fillStyle = '#667eea';
                    ctx.fillRect(0, 0, canvas.width, 60);
                    
                    // 添加标题文字
                    ctx.fillStyle = '#ffffff';
                    ctx.font = 'bold 24px Arial';
                    ctx.textAlign = 'center';
                    ctx.fillText('邀请二维码', canvas.width / 2, 35);
                }
                
                // 计算二维码在背景中的位置和尺寸（右下角）
                const qrSize = Math.min(canvas.width * 0.6, canvas.height * 0.6, 250);
                const margin = 20; // 距离边缘的边距
                const qrX = canvas.width - qrSize - margin;
                const qrY = canvas.height - qrSize - margin;
                
                // 绘制二维码
                ctx.drawImage(qrImage, qrX, qrY, qrSize, qrSize);
                
                // 添加二维码边框
                ctx.strokeStyle = '#667eea';
                ctx.lineWidth = 3;
                ctx.strokeRect(qrX - 2, qrY - 2, qrSize + 4, qrSize + 4);
                
                // 添加说明文字（在二维码上方）
                ctx.fillStyle = '#333333';
                ctx.font = '12px Arial';
                ctx.textAlign = 'center';
                ctx.fillText('扫描注册', qrX + qrSize / 2, qrY - 10);
                
                // 添加邀请码信息（在二维码下方）
                const inviteCode = '<?php echo htmlspecialchars($user['invite_code'] ?? ''); ?>';
                if (inviteCode && inviteCode !== '未生成') {
                    ctx.fillStyle = '#666666';
                    ctx.font = '10px Arial';
                    ctx.textAlign = 'center';
                    ctx.fillText(`邀请码：${inviteCode}`, qrX + qrSize / 2, qrY + qrSize + 15);
                }
                
                // 转换为blob并下载
                canvas.toBlob(function(blob) {
                    if (!blob) {
                        showToast('图片生成失败', 'error');
                        return;
                    }
                    
                    const url = URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = '分享邀请二维码_<?php echo htmlspecialchars($username); ?>_<?php echo htmlspecialchars($user['invite_code'] ?? ''); ?>.png';
                    a.style.display = 'none';
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    URL.revokeObjectURL(url);
                    showToast('分享二维码已下载！', 'success');
                }, 'image/png', 0.9);
                
            } catch (error) {
                console.error('下载失败:', error);
                showToast('下载失败: ' + error.message, 'error');
            }
        }
        
        // 刷新分享二维码
        async function refreshShareQRCode() {
            try {
                const inviteLink = '<?php echo 'http://' . $_SERVER['HTTP_HOST'] . '/login.php?invite=' . urlencode($user['invite_code'] ?? ''); ?>';
                if (!inviteLink) {
                    showToast('邀请链接未找到', 'error');
                    return;
                }
                
                // 使用新的API生成二维码
                const response = await fetch('/api/generate_qr.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        text: inviteLink,
                        size: 300,
                        error_correction: 'L',
                        margin: 4,
                        module_size: 3
                    })
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const result = await response.json();
                
                if (result.success && result.data && result.data.base64) {
                    const qrImage = document.getElementById('share-qr-code-image');
                    qrImage.src = result.data.base64;
                    showToast('分享二维码已刷新', 'success');
                } else {
                    throw new Error(result.error || '二维码生成失败');
                }
                
            } catch (error) {
                console.error('刷新分享二维码失败:', error);
                showToast('分享二维码刷新失败', 'error');
            }
        }
        
        // 点击弹窗外部关闭弹窗
        window.onclick = function(event) {
            const shareModal = document.getElementById('share-modal');
            if (event.target === shareModal) {
                closeModal('share-modal');
            }
        }
        
        // 页面加载完成后为分享按钮添加动画效果
        document.addEventListener('DOMContentLoaded', function() {
            const shareBtn = document.querySelector('.share-btn');
            if (shareBtn) {
                // 延迟添加动画类，让按钮更有吸引力
                setTimeout(() => {
                    shareBtn.classList.add('animate');
                }, 1000);
                
                // 添加点击波纹效果
                shareBtn.addEventListener('click', function(e) {
                    const ripple = document.createElement('span');
                    const rect = this.getBoundingClientRect();
                    const size = Math.max(rect.width, rect.height);
                    const x = e.clientX - rect.left - size / 2;
                    const y = e.clientY - rect.top - size / 2;
                    
                    ripple.style.width = ripple.style.height = size + 'px';
                    ripple.style.left = x + 'px';
                    ripple.style.top = y + 'px';
                    ripple.classList.add('ripple');
                    
                    this.appendChild(ripple);
                    
                    setTimeout(() => {
                        ripple.remove();
                    }, 600);
                });
            }
        });
    </script>
</body>
</html>
